package hl.demosample.app.weight.downloadpicture;

import android.app.ActivityManager;
import android.content.Context;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

public class CommonUtils {
    // 序列化加密
    public static String objectToString(Object o) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(o);
        oos.flush();
        oos.close();
        bos.close();
        return new String(Base64.encode(bos.toByteArray()));
    }

    // 反序列化字符串为对象
    public static Object stringToObjcet(String object) throws Exception {
        ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(object));
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object o = ois.readObject();
        bis.close();
        ois.close();
        return o;
    }

    // 格式化unixtime
    public static String formatUnixTime(String unixTime, String formatString) {
        SimpleDateFormat df = new SimpleDateFormat(formatString);
        return df.format(Long.valueOf(unixTime));
    }

    // 根据类名判断服务是否在运行中。
    public static boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }
}
